package controller

import (
	"myginproject/internal/controller/ws"
	"myginproject/internal/models"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
)

func SendMessage(db *gorm.DB, hub *ws.Hub) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req struct {
			Content     string `json:"content" binding:"required"`
			GroupID     string `json:"group_id" binding:"required"` // 改为GroupID
			ContentType int    `json:"content_type" default:"1"`
		}

		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		// 获取当前用户
		userID, exists := c.Get("user_id")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未授权"})
			return
		}

		// 获取用户信息（假设可以从上下文中获取）
		userName, _ := c.Get("user_name")
		userAvatar, _ := c.Get("user_avatar")

		// 创建消息记录
		msgID := uuid.New().String()
		now := time.Now()

		// // 保存消息到数据库
		// messageRecord := models.WsChatRecord{
		// 	MsgID:       msgID,
		// 	GroupID:     req.GroupID,                  // 改为GroupID
		// 	SenderID:    strconv.FormatUint(uint64(userID.(uint)), // 转换为string
		// 	Content:     req.Content,
		// 	ContentType: req.ContentType,
		// 	Status:      models.MsgStatusSent,
		// 	CreatedAt:   now,
		// 	UpdatedAt:   now,
		// }

		// if err := db.Create(&messageRecord).Error; err != nil {
		// 	c.JSON(http.StatusInternalServerError, gin.H{"error": "消息保存失败"})
		// 	return
		// }

		// 创建WebSocket消息
		wsMessage := &models.WsMessage{
			Event:     "message",
			MsgID:     msgID,
			GroupID:   req.GroupID,                                   // 改为GroupID
			SenderID:  strconv.FormatUint(uint64(userID.(uint)), 10), // 转换为string，添加缺失的逗号
			Sender:    userName.(string),                             // 添加发送者名称
			Avatar:    userAvatar.(string),                           // 添加发送者头像
			Content:   req.Content,
			Timestamp: now,
		}

		// 通过WebSocket广播消息
		hub.Broadcast <- wsMessage

		// 更新群组最后活跃时间
		// db.Model(&models.WsGroup{}).
		// 	Where("group_id = ?", req.GroupID).
		// 	Update("last_active", now)

		c.JSON(http.StatusOK, gin.H{
			"message": "消息发送成功",
			"data":    wsMessage,
		})
	}
}
